import markdown
from django.shortcuts import render, get_object_or_404

# Create your views here.
from django.http import HttpResponse

from blog.models import Post, Category, Tag


def index(request):
    posts = Post.objects.all()
    print(posts)

    return render(request,'blog/index.html',context={'posts':posts
        # 'title':'我的博客首页',
        # 'welcome':'欢迎访问我的博客首页'
    })
def detail(request,id):
    post = get_object_or_404(Post,id=id)
    # 记得在顶部引入 markdown 模块
    # extensions，它是对 Markdown 语法的拓展，这里我们使用了三个拓展
    # 1). extra 本身包含很多拓展，
    # 2). codehilite 是语法高亮拓展
    # 3). toc 则允许我们自动生成目录
    post.body = markdown.markdown(post.body,
                                  extensions=[
                                      'markdown.extensions.extra',
                                      'markdown.extensions.codehilite',
                                      'markdown.extensions.toc',
                                  ])
    post.increase_views()
    return render(request ,'blog/detail.html',context={'post':post})

    # return HttpResponse('欢迎访问我的博客首页')

def category(request, id):
    # 记得在开始部分导入 Category 类
    cate = get_object_or_404(Category, id=id)
    post_list = Post.objects.filter(category=cate).order_by('-created_time')
    return render(request, 'blog/index.html', context={'posts': post_list})

def archives(request, year, month):
    post_list = Post.objects.filter(created_time__year=year,created_time__month=month).order_by('-created_time')
    return render(request, 'blog/index.html', context={'posts': post_list})

def tag(request,id):
    tags = get_object_or_404(Tag, id=id)
    post_list = Post.objects.filter(tags=tags).order_by('-created_time')
    return render(request, 'blog/index.html', context={'posts': post_list})

